package anonymouschat.security;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

import anonymouschat.utils.Print;

/**
 * Class with static methods used to generate AES keys from password and salt, 
 * as well as system randomness
 * @author Jason
 *
 */
public class Keys {

	/**
	 * Create an AES key from the password and the salt provided
	 * 
	 * @param password
	 * @param salt
	 * @return
	 */
	public static SecretKey createAESKey(String password, byte[] salt) {

		SecretKeyFactory factory = null;
		try {
			factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
		} catch (NoSuchAlgorithmException e1) {
			Print.error("Failed to create secret key.", e1);
		}
		// Password passed encryption, combined with the salt 128 bits long
		KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.clone(),
				1024, 128);
		SecretKey tmp = null;
		SecretKey secret = null;
		try {
			tmp = factory.generateSecret(spec);
		} catch (InvalidKeySpecException e) {
			Print.error("Failed to generate secret key.", e);
		}
		// use PBE key to create the AES key
		secret = new SecretKeySpec(tmp.getEncoded(), "AES");

		// return the AES key
		return secret;
	}

	/**
	 * Generate AES key
	 * 
	 * @return SecretKey an AES key
	 * @throws NoSuchAlgorithmException
	 */
	public static SecretKey generateAESkey() throws NoSuchAlgorithmException {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		kgen.init(128);
		return kgen.generateKey();
	}

}
